#!/usr/bin/env bash

# SPDX-FileCopyrightText: SAP SE or an SAP affiliate company and Gardener contributors
#
# SPDX-License-Identifier: Apache-2.0

# Configuration Options:
#
# COMPONENT_PREFIXES: Set the image prefix that should be used to
#                     determine if an image is defined by another component.
#                     Defaults to "europe-docker.pkg.dev/gardener-project/releases/gardener"
#
# COMPONENT_CLI_ARGS: Set all component-cli arguments.
#                     This should be used with care as all defaults are overwritten.
#

set -e

repo_root_dir="$1"
descriptor_out_file="${COMPONENT_DESCRIPTOR_PATH}"

echo "Enriching component descriptor from ${BASE_DEFINITION_PATH}"

image_vector_path=""
if [[ -f "$repo_root_dir/charts/images.yaml" ]]; then
  image_vector_path="$repo_root_dir/charts/images.yaml"
elif [[ -f "$repo_root_dir/imagevector/images.yaml" ]]; then
  image_vector_path="$repo_root_dir/imagevector/images.yaml"
elif [[ -f "$repo_root_dir/imagevector/containers.yaml" ]]; then
  image_vector_path="$repo_root_dir/imagevector/containers.yaml"
fi

if [[ ! -z "$image_vector_path" ]]; then
  # default environment variables
  if [[ -z "${COMPONENT_PREFIXES}" ]]; then
    COMPONENT_PREFIXES="europe-docker.pkg.dev/gardener-project/releases/gardener,europe-docker.pkg.dev/gardener-project/snapshots/gardener"
  fi

  if [[ -z "${COMPONENT_CLI_ARGS}" ]]; then
    COMPONENT_CLI_ARGS="
    --comp-desc ${BASE_DEFINITION_PATH} \
    --image-vector "$image_vector_path" \
    --component-prefixes "${COMPONENT_PREFIXES}" \
    "
  fi

  # translates all images defined the containers.yaml into component descriptor resources.
  # For detailed documentation see https://github.com/gardener/component-cli/blob/main/docs/reference/components-cli_image-vector_add.md
  component-cli image-vector add ${COMPONENT_CLI_ARGS}
fi

cp "${BASE_DEFINITION_PATH}" "${descriptor_out_file}"
